// 游戏界面主页JavaScript

class GameHome {
    constructor() {
        this.init();
    }

    init() {
        this.setupEventListeners();
        this.loadGameStats();
        this.setupAnimations();
        this.setupGameModeSelection();
    }

    // 设置事件监听器
    setupEventListeners() {
        // 游戏模式卡片点击事件
        document.querySelectorAll('.game-mode-card').forEach(card => {
            card.addEventListener('click', (e) => {
                if (!e.target.closest('.game-btn')) {
                    this.selectGameMode(card);
                }
            });
        });

        // 开始游戏按钮事件
        document.querySelectorAll('.start-game-btn').forEach(btn => {
            btn.addEventListener('click', (e) => {
                const mode = e.target.closest('.game-mode-card').dataset.mode;
                this.startGame(mode);
            });
        });

        // 键盘快捷键
        document.addEventListener('keydown', (e) => {
            this.handleKeyboardShortcuts(e);
        });

        // 窗口调整大小
        window.addEventListener('resize', () => {
            this.handleResize();
        });
    }

    // 加载游戏统计数据
    loadGameStats() {
        // 模拟从本地存储加载数据
        const stats = {
            totalGames: localStorage.getItem('totalGames') || 0,
            highScore: localStorage.getItem('highScore') || 0,
            totalTime: localStorage.getItem('totalTime') || '0:00',
            achievements: localStorage.getItem('achievements') || 0
        };

        this.updateStatsDisplay(stats);
    }

    // 更新统计显示
    updateStatsDisplay(stats) {
        document.getElementById('total-games').textContent = stats.totalGames;
        document.getElementById('high-score').textContent = stats.highScore;
        document.getElementById('total-time').textContent = stats.totalTime;
        document.getElementById('achievements').textContent = stats.achievements;
    }

    // 设置动画效果
    setupAnimations() {
        // 滚动动画
        this.setupScrollAnimations();
        
        // 鼠标悬停效果
        this.setupHoverEffects();
        
        // 加载动画
        this.showLoadingAnimation();
    }

    // 滚动动画
    setupScrollAnimations() {
        const observerOptions = {
            threshold: 0.1,
            rootMargin: '0px 0px -50px 0px'
        };

        const observer = new IntersectionObserver((entries) => {
            entries.forEach(entry => {
                if (entry.isIntersecting) {
                    entry.target.classList.add('animate__animated', 'animate__fadeInUp');
                }
            });
        }, observerOptions);

        // 观察所有需要动画的元素
        document.querySelectorAll('.game-mode-card, .game-stats, .game-control-panel').forEach(el => {
            observer.observe(el);
        });
    }

    // 鼠标悬停效果
    setupHoverEffects() {
        const cards = document.querySelectorAll('.game-mode-card');
        
        cards.forEach(card => {
            card.addEventListener('mouseenter', () => {
                this.enhanceCardEffect(card);
            });
            
            card.addEventListener('mouseleave', () => {
                this.resetCardEffect(card);
            });
        });
    }

    // 增强卡片效果
    enhanceCardEffect(card) {
        const icon = card.querySelector('.mode-icon');
        if (icon) {
            icon.style.transform = 'scale(1.2) rotate(5deg)';
            icon.style.boxShadow = '0 0 30px rgba(0, 255, 136, 0.7)';
        }
    }

    // 重置卡片效果
    resetCardEffect(card) {
        const icon = card.querySelector('.mode-icon');
        if (icon) {
            icon.style.transform = 'scale(1)';
            icon.style.boxShadow = 'none';
        }
    }

    // 显示加载动画
    showLoadingAnimation() {
        const loadingElement = document.createElement('div');
        loadingElement.className = 'loading-spinner';
        loadingElement.style.position = 'fixed';
        loadingElement.style.top = '50%';
        loadingElement.style.left = '50%';
        loadingElement.style.transform = 'translate(-50%, -50%)';
        loadingElement.style.zIndex = '9999';
        
        document.body.appendChild(loadingElement);
        
        // 模拟加载过程
        setTimeout(() => {
            loadingElement.remove();
            this.showWelcomeMessage();
        }, 2000);
    }

    // 显示欢迎消息
    showWelcomeMessage() {
        const welcomeMsg = document.createElement('div');
        welcomeMsg.className = 'alert alert-success position-fixed top-0 start-50 translate-middle-x mt-3';
        welcomeMsg.style.zIndex = '9999';
        welcomeMsg.innerHTML = `
            <strong>欢迎来到贪吃蛇游戏！</strong> 选择游戏模式开始挑战吧！
        `;
        
        document.body.appendChild(welcomeMsg);
        
        // 3秒后自动消失
        setTimeout(() => {
            welcomeMsg.remove();
        }, 3000);
    }

    // 设置游戏模式选择
    setupGameModeSelection() {
        const modes = document.querySelectorAll('.game-mode-card');
        
        modes.forEach(mode => {
            mode.addEventListener('click', () => {
                // 移除所有激活状态
                modes.forEach(m => m.classList.remove('active'));
                // 添加当前激活状态
                mode.classList.add('active');
                
                // 更新选中效果
                this.updateSelectedMode(mode);
            });
        });
    }

    // 更新选中模式
    updateSelectedMode(mode) {
        const modeName = mode.querySelector('.card-title').textContent;
        const modeDescription = mode.querySelector('.card-text').textContent;
        
        // 更新控制面板显示
        const controlPanel = document.querySelector('.game-control-panel');
        if (controlPanel) {
            controlPanel.querySelector('.selected-mode').textContent = modeName;
            controlPanel.querySelector('.mode-description').textContent = modeDescription;
        }
    }

    // 选择游戏模式
    selectGameMode(card) {
        const mode = card.dataset.mode;
        console.log(`选择游戏模式: ${mode}`);
        
        // 添加视觉反馈
        card.style.transform = 'scale(0.95)';
        setTimeout(() => {
            card.style.transform = '';
        }, 150);
    }

    // 开始游戏
    startGame(mode) {
        console.log(`开始游戏: ${mode}`);
        
        // 显示加载状态
        this.showGameLoading(mode);
        
        // 模拟游戏加载
        setTimeout(() => {
            // 根据模式跳转到不同页面
            if (mode === 'adventure') {
                // 闯关模式跳转到难度选择页面
                window.location.href = 'choose.html';
            } else if (mode === 'versus') {
                // 对决模式跳转到对决选择页面
                window.location.href = 'duel-choose.html';
            } else {
                // 其他模式跳转到游戏页面
                window.location.href = `game.html?mode=${mode}`;
            }
        }, 1000);
    }

    // 显示游戏加载状态
    showGameLoading(mode) {
        const loadingOverlay = document.createElement('div');
        loadingOverlay.className = 'position-fixed top-0 start-0 w-100 h-100 d-flex align-items-center justify-content-center';
        loadingOverlay.style.background = 'rgba(0, 0, 0, 0.8)';
        loadingOverlay.style.zIndex = '9999';
        
        loadingOverlay.innerHTML = `
            <div class="text-center text-white">
                <div class="loading-spinner mb-3"></div>
                <h4>正在加载 ${this.getModeName(mode)} 模式...</h4>
                <p>请稍候...</p>
            </div>
        `;
        
        document.body.appendChild(loadingOverlay);
    }

    // 获取模式名称
    getModeName(mode) {
        const modeNames = {
            'classic': '经典',
            'adventure': '闯关',
            'versus': '对决',
            'boss': 'BOSS战'
        };
        return modeNames[mode] || mode;
    }

    // 处理键盘快捷键
    handleKeyboardShortcuts(e) {
        switch(e.key) {
            case '1':
                e.preventDefault();
                this.startGame('classic');
                break;
            case '2':
                e.preventDefault();
                this.startGame('adventure');
                break;
            case '3':
                e.preventDefault();
                this.startGame('versus');
                break;
            case '4':
                e.preventDefault();
                this.startGame('boss');
                break;
            case 'Escape':
                // 可以添加退出或菜单功能
                break;
        }
    }

    // 处理窗口调整大小
    handleResize() {
        // 调整响应式布局
        this.adjustLayoutForScreenSize();
    }

    // 根据屏幕尺寸调整布局
    adjustLayoutForScreenSize() {
        const width = window.innerWidth;
        const gameCards = document.querySelectorAll('.game-mode-card');
        
        if (width < 768) {
            // 移动端布局调整
            gameCards.forEach(card => {
                card.style.marginBottom = '1rem';
            });
        } else {
            // 桌面端布局调整
            gameCards.forEach(card => {
                card.style.marginBottom = '';
            });
        }
    }

    // 工具函数：格式化时间
    formatTime(seconds) {
        const mins = Math.floor(seconds / 60);
        const secs = seconds % 60;
        return `${mins}:${secs.toString().padStart(2, '0')}`;
    }

    // 工具函数：随机颜色生成
    getRandomColor() {
        const colors = ['#00ff88', '#00ccff', '#ff6b6b', '#ffd93d', '#6bcf7f'];
        return colors[Math.floor(Math.random() * colors.length)];
    }
}

// 页面加载完成后初始化
document.addEventListener('DOMContentLoaded', () => {
    new GameHome();
});

// 导出供其他模块使用
if (typeof module !== 'undefined' && module.exports) {
    module.exports = GameHome;
}